from flask import Flask, g, request
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from toutiao.settings import config_dict, setup_log
from snowflake.id_worker import IdWorker


import redis

# 多种配置使用
Config = config_dict['dev']
# 配置日志
setup_log(Config)

app = Flask(__name__)


app.config.from_object(Config)

# 创建SQLAlchemy实例
db = SQLAlchemy(app)

# redis配置
app.redis_store = redis.Redis(host=Config.REDIS_HOST, port=Config.REDIS_PORT, db=9)

# 跨域
CORS(app)

# 雪花算法
# 创建Snowflake ID worker
app.id_worker = IdWorker(Config.DATACENTER_ID,
                         Config.WORKER_ID,
                        Config.SEQUENCE)

# 注册蓝图
# home
from toutiao.apps.home import home_blueprint
app.register_blueprint(home_blueprint)
# user
from toutiao.apps.user import user_blueprint
app.register_blueprint(user_blueprint)


@app.route('/')
def Index():
    return 'index...'

from auth.auth_iwt import verify_jwt
# 验证token,请求钩子函数
@app.before_request
def before_request():
    """验证token"""
    # 初始化用户id
    g.user_id =None
    g.refresh = None
    # 获取请求头中的token
    authorization = request.headers.get('Authorization')
    if authorization and authorization.startswith('Bearer '):
        token = authorization[7:]
        # 通过token获取user_id
        payload = verify_jwt(token)
        if payload:
            g.user_id = payload.get('user_id')
            g.refresh = payload.get('refresh')


